/*
 * @(#)Struts2Utils.java     2009-5-9
 *
 * Copyright (c) 2008-2009 ZJPII Co,.Ltd - All Rights Reserved.
 *
 *====================================================================
 * The ZJPII Software License, Version 1.0
 *
 * This software is the confidential and proprietary information of ZJPII
 * Software Co.Ltd. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ZJPII.
 */
package com.desktopmng.core.utils;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

/**
 * Description:Struts2 Utils类.
 * 实现获取Request/Response/Session与绕过jsp/freemaker直接输出文本的简化函数.
 * 
 * @author GaoXJ
 * @version 2009-5-9 下午05:04:56
 * @since version1.0
 */
public class Struts2Utils {

	// header 常量定义
	private static final String ENCODING_PREFIX = "encoding";
	private static final String NOCACHE_PREFIX = "no-cache";
	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final boolean NOCACHE_DEFAULT = true;
	private static Log logger = LogFactory.getLog(Struts2Utils.class);

	private Struts2Utils() {
	}

	// 取得Request/Response/Session的简化函数 //
	/**
	 * 取得HttpSession的简化方法.
	 */
	public static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	/**
	 * 取得HttpRequest的简化方法.
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 取得HttpResponse的简化方法.
	 */
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	// 绕过jsp/freemaker直接输出文本的函数 //
	/**
	 * 直接输出内容的简便函数.
	 * 
	 * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain",
	 * "hello", "no-cache:false"); render("text/plain", "hello", "encoding:GBK",
	 * "no-cache:false");
	 * 
	 * @param headers
	 *            可变的header数组，目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
	 */
	public static void render(final String contentType,
			final String content, final String... headers) {
		try {
			// 分析headers参数
			String encoding = ENCODING_DEFAULT;
			boolean noCache = NOCACHE_DEFAULT;
			for (String header : headers) {
				// System.out.println(header);
				String headerName = StringUtils.substringBefore(
						header, ":");
				String headerValue = StringUtils.substringAfter(
						header, ":");
				// System.out.println(headerName);
				// System.out.println(headerValue);
				if (StringUtils.equalsIgnoreCase(headerName,
						ENCODING_PREFIX)) {
					encoding = headerValue;
				} else if (StringUtils.equalsIgnoreCase(headerName,
						NOCACHE_PREFIX)) {
					noCache = Boolean.parseBoolean(headerValue);
				} else
					throw new IllegalArgumentException(headerName
							+ "不是一个合法的header类型");
			}
			HttpServletResponse response = ServletActionContext
					.getResponse();
			// 设置headers参数
			String fullContentType = contentType + ";charset="
					+ encoding;
			response.setContentType(fullContentType);
			if (noCache) {
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
			}
			response.getWriter().write(content);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出文本.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderText(final String text,
			final String... headers) {
		render("text/plain", text, headers);
	}

	/**
	 * 直接输出HTML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html,
			final String... headers) {
		render("text/html", html, headers);
	}
	/**
	 * 直接输出HTML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html) {
		render("text/html", html, "encoding:UTF-8", "no-cache:true");
	}
	/**
	 * 直接输出HTML.
	 * 
	 * @see #render(String, String, String...)
	 * flag 为1时，标识为成功；flag为0时，标识为失败；msg为相应的提示信息
	 */
	public static void renderHtml(String flag,String msg) {
//		msg=msg.replaceAll(regex, replacement)
		String html="<script type=\"text/javascript\">parent.afterOperation('"+flag+"','"+msg+"');history.back();</script>";
		render("text/html", html, "encoding:UTF-8", "no-cache:true");
	}
	
	public static void renderHtmlSelf(String flag,String msg) {
//		msg=msg.replaceAll(regex, replacement)
		String html="<script type=\"text/javascript\">afterOperationWin('"+flag+"','"+msg+"');</script>";
		render("text/html", html, "encoding:UTF-8", "no-cache:true");
	}
	
	/**
	 * 调用页面的afterOperation方法重新刷新页面
	 * flag 为1时，标识为成功；flag为0时，标识为失败；msg为相应的提示信息
	 * @param flag
	 * @param msg
	 */
	public static void reloadHtml(String flag ,String msg){
		String html="<script type=\"text/javascript\">parent.afterOperation('"+flag+"','"+msg+"');</script>";
		render("text/html", html, "encoding:UTF-8", "no-cache:true");
	}
	
	public static void renderHtmlOpener(String flag,String msg) {
//		msg=msg.replaceAll(regex, replacement)
		String html="";
		if("1".equals(flag)){
			html="<script type=\"text/javascript\">window.opener.afterOperation('"+flag+"','"+msg+"');window.close();</script>";
		}else if("3".equals(flag)){
			html="<script type=\"text/javascript\">window.opener.afterOperation('"+flag+"','"+msg+"');window.close();</script>";
		}else {
			html="<script type=\"text/javascript\">window.opener.afterOperation('"+flag+"','"+msg+"');history.back();</script>";
		}		
		render("text/html", html, "encoding:UTF-8", "no-cache:true");
	}
	public static void renderHtmlParentOpener(String flag,String msg) {
//		msg=msg.replaceAll(regex, replacement)
		String html="";
		if("1".equals(flag)){
			html="<script type=\"text/javascript\">	parent.window.opener.afterOperation('"+flag+"','"+msg+"');parent.window.close();</script>";
		}else {
			html="<script type=\"text/javascript\">	parent.window.opener.afterOperation('"+flag+"','"+msg+"');history.back();</script>";
		}		
		render("text/html", html, "encoding:UTF-8", "no-cache:true");
	}
	/**
	 * 直接输出JavaScript.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderScript(final String js,
			final String... headers) {
		render("text/javascript", js, headers);
	}
	
	/**
	 * 直接输出JavaScript.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderScript(final String js) {
		render("text/javascript", js,"encoding:UTF-8", "no-cache:true");
	}

	/**
	 * 直接输出XML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(final String xml,
			final String... headers) {
		render("text/xml", xml, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param string
	 *            json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String string,
			final String... headers) {
		render("application/json", string, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param string
	 *            json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String json) {
		render("application/json", json,"encoding:UTF-8", "no-cache:true");
	}
	/**
	 * 直接输出JSON.
	 * 
	 * @param map
	 *            Map对象,将被转化为json字符串.
	 * @see #render(String, String, String...)
	 */
	@SuppressWarnings("unchecked")
	public static void renderJson(final Map map,
			final String... headers) {
		String jsonString = new JSONObject(map).toString();
		renderJson(jsonString, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param object
	 *            Java对象,将被转化为json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final Object object,
			final String... headers) {
		String jsonString = new JSONObject(object).toString();
		renderJson(jsonString, headers);
	}

	/**
	 * Description:获取真实客户端IP地址
	 * @return
	 */
	public static String getIpAddr() {
		String ip = getRequest().getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0
				|| "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0
				|| "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0
				|| "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getRemoteAddr();
		}
		if(null!=ip) {
			String[] ips = ip.split(",");
			ip = ips[0];
		}
		return ip;
	}
}
